package com.lanyou.cook.service;

import java.io.IOException;
import java.util.stream.Stream;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.service.vo.InterfaceExecutionParam;

/*
 * 监控正在执行中的接口
 */

@Service
public class RunningInterfaceWatcher {

	@Autowired
	private CuratorService curatorService;

	private PathChildrenCache runningInterfaceCache;

	@PostConstruct
	private void init() throws Exception {
		if (!curatorService.isEnable())
			return;
		runningInterfaceCache = new PathChildrenCache(curatorService.getClient(), Constants.ZOOKEPPER_PATH_RUNNING_INTERFACE,
				true);
		runningInterfaceCache.start(StartMode.BUILD_INITIAL_CACHE);
	}
	
	@PreDestroy
	private void close(){
		closeCache();
	}
	
	private void closeCache(){
		if(runningInterfaceCache != null){
			try {
				runningInterfaceCache.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			runningInterfaceCache = null;
		}
	}

	public Stream<InterfaceExecutionParam> runningInterfaceInfoStream(){
		if (runningInterfaceCache == null)
			return Stream.empty();
		return runningInterfaceCache.getCurrentData().stream().map(cd -> InterfaceExecutionParam.deserialize(cd.getData()));
	}
	
	public boolean isRunning(String systemInterfaceId) {
		return runningInterfaceInfoStream().anyMatch(iep -> StringUtils.equals(systemInterfaceId, iep.getSystemInterfaceId()));
	}

}
